<template>
  <div class="write-answer">
    <!-- 问卷卡片 -->
    <el-card v-if="questionsAndOptions.length" class="questionnaire-card">
      <!-- 问卷头部 -->
      <div class="header">
        <h2 class="title">{{ title }}</h2>
        <p class="description">{{ description }}</p>
      </div>

      <!-- 题目列表 -->
      <div class="questions-list">
        <div
          v-for="(item, index) in questionsAndOptions"
          :key="item.question.id || index"
          class="question-row"
        >
          <div class="q-head">
            <span class="q-index">{{ index + 1 }}.</span>
            <span class="q-text">{{ item.question.content }}</span>
            <span v-if="item.question.required" class="q-required">*</span>
          </div>

          <!-- 单选 -->
          <el-radio-group
            v-if="item.question.type === 'radio'"
            v-model="answers[item.question.id]"
            class="control-group"
          >
            <div
              v-for="(opt, oIndex) in item.options"
              :key="opt.id || oIndex"
              class="option-line"
            >
              <el-radio :label="opt.id">
                <span class="opt-text">{{ opt.optionContent }}</span>
              </el-radio>
              <el-input
                v-if="isOther(opt) && answers[item.question.id] === opt.id"
                v-model="otherAnswers[item.question.id]"
                placeholder="请输入其他内容"
                size="small"
                class="other-input"
              />
            </div>
          </el-radio-group>

          <!-- 多选 -->
          <el-checkbox-group
            v-else-if="item.question.type === 'checkbox'"
            v-model="answers[item.question.id]"
            class="control-group"
          >
            <div
              v-for="(opt, oIndex) in item.options"
              :key="opt.id || oIndex"
              class="option-line"
            >
              <el-checkbox :label="opt.id">
                <span class="opt-text">{{ opt.optionContent }}</span>
              </el-checkbox>
              <el-input
                v-if="isOther(opt) && answers[item.question.id]?.includes(opt.id)"
                v-model="otherAnswers[item.question.id]"
                placeholder="请输入其他内容"
                size="small"
                class="other-input"
              />
            </div>
          </el-checkbox-group>

          <!-- 简答题 -->
          <div v-else-if="item.question.type === 'text'" class="text-line">
            <el-input
              type="textarea"
              v-model="answers[item.question.id]"
              placeholder="请输入您的回答"
              :rows="3"
            />
          </div>

          <el-divider />
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="actions">
        <el-button type="primary" @click="handleSubmit">提交问卷</el-button>
      </div>
    </el-card>

    <!-- 空状态 -->
    <el-empty v-else description="问卷不存在或已被删除" />
  </div>

  <!-- 登录弹窗 -->
  <!-- <el-dialog title="登录" v-model="dialogVisible" width="400px">
    <el-form :model="loginForm" label-width="80px">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="loginForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleLogin">登录</el-button>
    </div>
  </el-dialog> -->
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const qid = route.params.id

const title = route.query.title || '未命名问卷'
const description = route.query.description || '暂无描述'
const endTime = route.query.endTime || '未知时间'



const questionsAndOptions = reactive([])
const answers = reactive({})
const otherAnswers = reactive({})

// 用于弹出登录框的状态
const dialogVisible = ref(false)

// 登录表单数据
const loginForm = reactive({
  name: '',
  password: '',
  qid: qid
})

// 判断“其他”选项
function isOther(opt) {
  if (!opt) return false
  if (opt.optionName && /other|OTHER|OTHER_OPTION|OTHER_FLAG/i.test(opt.optionName)) return true
  const txt = String(opt.optionContent || '').trim()
  return txt === '其他' || txt === '其它' || txt.includes('其他') || txt.includes('其它')
}

// 登录处理
const handleLogin = async () => {
  if (!loginForm.name || !loginForm.password) {
    ElMessage.warning('请填写用户名和密码')
    return
  }

  // 模拟后端登录请求，实际应替换为你的登录接口
  const response = await request.post('/user/qlogin', loginForm) // 替换为你的登录接口

  if (response.data.code === 200) {
    // 登录成功，将用户信息存储到 localStorage
    localStorage.setItem('user', JSON.stringify(response.data.data))
    // console.log('登录成功，用户信息已存储到 localStorage',localStorage.getItem('user'))
    ElMessage.success('登录成功！')
    dialogVisible.value = false // 关闭登录弹窗
  } else {
    ElMessage.error(response.data.message || '登录失败')
  }
}

// 提交问卷
const handleSubmit = async () => {
  
  // 获取登录用户信息
  //const user = JSON.parse(localStorage.getItem('user')) // 获取登录用户
  // console.log('sub',user)

  // if (!user) {
  //   // 如果没有登录，显示登录弹窗
  //   console.log('未登录，显示登录弹窗')
  //   dialogVisible.value = true
  //   return
  // }

  if (!questionsAndOptions.length) 
  {
    ElMessage.warning("请先填写问卷再提交")
    console.log("请先填写问卷再提交")
    return
  }

  const payload = questionsAndOptions.map(item => {
    const queId = item.question.id
    const queContent = item.question.content
    const selected = answers[queId]

    const optionsList = []

    if (item.question.type === 'radio') {
      const opt = item.options.find(o => o.id === selected)
      if (opt) {
        optionsList.push({
          id: opt.id,
          optionName: opt.optionName,
          optionContent: opt.optionContent,
          text: isOther(opt) ? otherAnswers[queId] || '' : ''
        })
      }
    } else if (item.question.type === 'checkbox') {
      selected?.forEach(selId => {
        const opt = item.options.find(o => o.id === selId)
        if (opt) {
          optionsList.push({
            id: opt.id,
            optionName: opt.optionName,
            optionContent: opt.optionContent,
            text: isOther(opt) ? otherAnswers[queId] || '' : ''
          })
        }
      })
    } else if (item.question.type === 'text') {
      optionsList.push({
        optionName: 'TEXT',
        optionContent: answers[queId] || '',
        text: answers[queId] || ''
      })
    }

    return {
      qid: item.qid,
      queId,
      queContent,
      //userId: user.id, // 使用登录用户的 ID
      options: optionsList
    }
  })

  try {
    const res = await request.post('/answer/addAnswer', payload)
    if (res.data.code !== 200) {
      ElMessage.error(res.data.message || '提交失败')
      return
    }
    ElMessageBox.alert('提交成功，感谢您的填写！', '提示', {
      confirmButtonText: '确定',
      callback: () => {
        window.close() // ✅ 直接关闭当前页面
      }
    })
  } catch (err) {
    console.error(err)
    ElMessage.error(err)
  }
}

// 在页面加载时添加事件监听器
window.addEventListener('beforeunload', function() {
  console.log("页面即将关闭，清除 localStorage");
  localStorage.clear(); // 清除 localStorage
});

onMounted(() => {
  console.log(localStorage)
  console.log(route.query)
  if (!qid) return
  request.get(`/question/listQuestionsByQid/${qid}`).then(res => {
    if (res.data.code === 200 && Array.isArray(res.data.data)) {
      questionsAndOptions.splice(0, questionsAndOptions.length)
      res.data.data.forEach(item => {
        const qIdField = item.question?.id || item.qid
        if (item.question?.type === 'checkbox') answers[qIdField] = []
        else answers[qIdField] = ''
        otherAnswers[qIdField] = ''

        questionsAndOptions.push({
          qid: item.qid,
          question: {
            id: qIdField,
            content: item.question?.content || '',
            type: item.question?.type || 'radio',
            required: item.question?.required || false
          },
          options: item.options || []
        })
      })
    } else {
      ElMessage.warning('未查询到问卷内容')
    }
  }).catch(err => {
    console.error(err)
    ElMessage.error('问卷加载失败')
  })
})
</script>

<style scoped>
.write-answer {
  max-width: 820px;
  margin: 0 auto;
  padding: 30px 24px 60px;
  color: #333;
  background: #fff;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
}

/* 头部 */
.header {
  text-align: center;
  margin-bottom: 40px;
}
.title {
  font-size: 24px;
  font-weight: 600;
  color: #222;
  margin-bottom: 10px;
}
.description {
  font-size: 15px;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.6;
}

/* 问题 */
.questions-list {
  display: flex;
  flex-direction: column;
  gap: 26px;
}
.question-row {
  text-align: left;
}
.q-head {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  margin-bottom: 10px;
  font-size: 16px;
  color: #222;
  line-height: 1.6;
}
.q-index {
  color: #409eff;
  font-weight: 600;
}
.q-required {
  color: #ff4d4f;
  margin-left: 4px;
}

/* 选项 */
.control-group {
  display: block;
}
.option-line {
  display: flex;
  flex-direction: column; /* 垂直排列选项和输入框 */
  gap: 6px;
  margin: 6px 0;
}
.option-line ::v-deep(.el-radio),
.option-line ::v-deep(.el-checkbox) {
  display: flex;
  align-items: flex-start;
  width: 100%;
  margin: 0;
  padding: 0;
}
.option-line ::v-deep(.el-radio__input),
.option-line ::v-deep(.el-checkbox__input) {
  margin-right: 8px;
  margin-top: 4px;
}
.option-line ::v-deep(.el-radio__label),
.option-line ::v-deep(.el-checkbox__label) {
  white-space: normal; /* 让标签换行显示 */
  margin-bottom: 6px; /* 选项和输入框之间的间距 */
}

/* 其他输入框 */
.other-input {
  margin-left: 0;
  margin-top: 6px; /* 输入框的顶部间距 */
  width: 100%; /* 宽度填满容器 */
}

/* 简答题 */
.text-line {
  margin-top: 8px;
}

/* 空状态 */
.el-empty {
  margin-top: 30px;
}

/* 提交按钮 */
.actions {
  text-align: center;
  margin-top: 50px;
}
</style>
